<?php
declare (strict_types = 1);

namespace app\common\model\Product;

use think\Model;
use app\common\model\Config;
use app\common\model\User\User;

/**
 * @mixin \think\Model
 */
class Product extends Model
{
    // 商品表
    protected $table = 'pre_product';

    protected $append = [
        'cover_cdn',   // 单图
        'vip_price',
        'thumbs_cdn'
    ];

    public function getThumbsCdnAttr($value,$data) {
        $cdn = Config::where(['key' => 'cdn'])->value('value');

        $thumbs = empty($data['thumbs']) ? [] : trim($data['thumbs']);
  
        if(empty($thumbs))
        {
            return $cdn .'/static/home/res/images/avatar/default.png';
        }

        //字符串替换
        $thumbs = str_replace("uploads/", $cdn."/uploads/", $thumbs);

        //在转换为数组
        // $list = explode(',', $thumbs);
        $list = json_decode($thumbs,true);

        if(count($list) > 0)
        {
            return $list;
        }
    }

    // 获取vip价格
    public function getVipPriceAttr($value,$data) {
        $userid = request()->param('userid',0);  

        $vip = User::where(['id' => $userid])->value('vip');

        if(!$vip) {
            return false;
        }

        $price = Vip::where(['proid' => $data['id'],'level' => $vip])->value('price');

        return $price;
    }

    public function getCoverCdnAttr($value,$data) {
        $cdn = Config::where(['key' => 'cdn'])->value('value');

        $thumbs = empty($data['thumbs']) ? [] : trim($data['thumbs']);
  
        if(empty($thumbs))
        {
            return $cdn .'/static/home/res/images/avatar/default.png';
        }

        //字符串替换
        $thumbs = str_replace("uploads/", $cdn."/uploads/", $thumbs);

        //在转换为数组
        // $list = explode(',', $thumbs);
        $list = json_decode($thumbs,true);

        if(count($list) > 0)
        {
            return $list[0];
        }

    }

}
